<template>
  <a-card style="width: 100%">
    <div class="header">
      <a-space class="left" direction="vertical" :size="[8, 12]">
        <Condition
          :condition="condition"
          :btns="['reset']"
          @search="onSearch"
          @reset="conditionReset"
        ></Condition>
        <div class="title">共筛选出 {{ pagination.total }} 条数据</div>
      </a-space>
      <a-space class="right" direction="vertical" :size="[8, 12]">
        <a-input-search
          v-model:value="templateName"
          placeholder="请输入健康监测名称"
          style="width: 220px"
          @search="onSearch"
        />
        <a-button type="primary" @click="modalShow()">新建健康监测</a-button>
      </a-space>
    </div>
    <div class="main">
      <a-table
        class="table"
        size="small"
        :loading="loading"
        :dataSource="List"
        :columns="columns"
        :pagination="pagination"
        @change="paginationChange"
        :sticky="{ offsetHeader: 0 }"
      >
        <template #bodyCell="{ column, text, index, record }">
          <template v-if="column.dataIndex === 'no'">
            {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
          </template>
          <template v-else-if="column.dataIndex === 'createTime'">
            {{ timeFilter(record[column.dataIndex]) }}
          </template>
          <template v-else-if="column.dataIndex === 'managePath'">
            <div class="tags" v-if="record[column.dataIndex]">
              <a-tag
                type="parmary"
                :title="item"
                v-for="(item, i) in record[column.dataIndex].split(', ')"
                :key="i"
                >{{ item }}</a-tag
              >
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <a-button type="link" @click="modalShow(record)">查看详情</a-button>
            <a-button
              type="link"
              @click="delForm(record)"
              :disabled="record.managePath ? true : false"
              >删除监测</a-button
            >
          </template>
          <template v-else>
            {{ text }}
          </template>
        </template>
      </a-table>
    </div>
    <a-modal
      width="720px"
      v-model:open="modal.open"
      :title="modal.title"
      ok-text="确认"
      cancel-text="取消"
      @ok="modalConfirm"
      :maskClosable="false"
    >
      <a-form
        class="modelForm"
        ref="modelForm"
        :colon="false"
        :model="formState"
        :label-col="{ style: { width: '110px' } }"
        labelAlign="left"
      >
        <a-form-item
          label="模板类型"
          name="templateAffiliation"
          required
          v-if="modal.type != 'detail' && !formState.id"
        >
          <a-select v-model:value="formState.templateAffiliation">
            <a-select-option label="公共模板" value="公共模板"> 公共模板 </a-select-option>
            <a-select-option label="个人模板" value="个人模板"> 个人模板 </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="健康监测名称"
          name="templateName"
          required
          :rules="{
            required: true,
            message: '健康监测名称不能为空',
            trigger: 'change',
            whitespace: true
          }"
        >
          <a-tooltip
            v-if="modal.type === 'detail'"
            placement="bottomLeft"
            :title="formState.templateName"
          >
            <a-input
              style="width: 350px"
              v-model:value="formState.templateName"
              autocomplete="off"
              placeholder="请输入健康监测名称"
              :maxlength="50"
              :disabled="modal.type === 'detail'"
            ></a-input>
          </a-tooltip>
          <a-input
            v-else
            style="width: 350px"
            v-model:value="formState.templateName"
            autocomplete="off"
            :maxlength="50"
            placeholder="请输入健康监测名称"
            :disabled="modal.type === 'detail'"
          ></a-input>
        </a-form-item>
        <a-form-item
          label="健康监测指标"
          :name="['content', 'sings']"
          required
          :rules="{
            required: true,
            message: '监测指标不能为空',
            trigger: 'change'
          }"
        >
          <a-select
            style="width: 100%"
            v-model:value="formState.content.sings"
            placeholder="请选择监测指标"
            :disabled="modal.type === 'detail'"
          >
            <a-select-option v-for="option in marks" :key="option.value" :value="option.value">{{
              option.label
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="执行日期"
          name="cronDate"
          :rules="[
            {
              required: true,
              validator: cronDateValidator
            }
          ]"
        >
          <div class="groups">
            <a-checkbox
              v-for="w in weeks"
              :key="w.value"
              :value="w.value"
              :checked="formState.content.cronDate.includes(w.value)"
              @change="changeCronDate($event)"
              :disabled="modal.type === 'detail'"
              >{{ w.label }}</a-checkbox
            >
            <a-checkbox
              :value="true"
              :checked="formState.content.cronDate.length === weeks.length"
              :indeterminate="
                formState.content.cronDate.length &&
                formState.content.cronDate.length !== weeks.length
                  ? true
                  : false
              "
              @change="weekAll()"
              :disabled="modal.type === 'detail'"
            >
              全选
            </a-checkbox>
          </div>
        </a-form-item>
        <a-form-item
          label="执行时间"
          :rules="[
            {
              required: true,
              validator: cronTimeValidator
            }
          ]"
          name="cronTime"
        >
          <div class="times">
            <div class="content" @click="pickerFocus()">
              <div v-if="modal.type === 'detail'" class="mask"></div>
              <a-tag
                class="tag"
                v-for="(tag, i) in formState.content.cronTime"
                @click.stop
                :key="i"
                closable
                @close="tagDel(formState.content.cronTime, i)"
                >{{ tag }}</a-tag
              >
            </div>
            <a-time-picker
              class="pick"
              v-model:open="formState.open"
              v-model:value="timePickerValue"
              format="HH:mm"
              valueFormat="HH:mm"
              @change="cronTimePush($event)"
              :disabled="modal.type === 'detail'"
            >
            </a-time-picker>
          </div>
        </a-form-item>
        <!-- <a-form-item required style="margin-bottom: -16px" label="健康监测内容:" labelAlign="left">
        </a-form-item>
        <a-form-item
          :name="['content', 'content']"
          required
          :rules="{
            required: true,
            message: '健康监测内容不能为空',
            trigger: 'change',
            whitespace: true
          }"
        >
          <a-textarea
            style="width: 100%"
            v-model:value="formState.content.content"
            placeholder="请输入健康监测内容"
            :maxlength="300"
            :rows="10"
            show-count
            :disabled="modal.type === 'detail'"
          />
        </a-form-item> -->
      </a-form>
      <template #footer>
        <template v-if="modal.type !== 'detail'">
          <a-button
            @click="
              () => {
                ;(modal.open = false), modelForm.clearValidate()
              }
            "
            >取消</a-button
          >
          <a-button :loading="modal.loading" type="primary" @click="modalConfirm">确认</a-button>
        </template>
        <template v-else>
          <a-button @click="modalUpdate" :disabled="!modal.allowUpdate">编辑</a-button>
          <a-button type="primary" @click="modal.open = false">确认</a-button>
        </template>
      </template>
    </a-modal>
  </a-card>
</template>

<script lang="ts" setup name="健康监测">
import { ref, reactive, onMounted } from 'vue'
import Condition from '@/components/Condition/index.vue'
import { createVNode } from 'vue'
import { getTemplateList, TemplateAdd, TemplateUpdate, TemplateDel } from '@/api/template'
import { ExclamationCircleFilled } from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import { useDict } from './components/getDict'
import { timeFilter } from '@/utils/tools'
import store from '@/store'
import _ from 'lodash'

const templateType = '健康监测'
const templateName = ref('')

const cronDateValidator = async (_, value) => {
  if (formState.content.cronDate.length > 0) {
  } else {
    return Promise.reject('请完善内容')
  }
  return Promise.resolve()
}

const cronTimeValidator = async (_, value) => {
  if (formState.content.cronTime.length > 0) {
  } else {
    return Promise.reject('请完善内容')
  }
  return Promise.resolve()
}

const weeks = [
  {
    label: '周一',
    value: '周一'
  },
  {
    label: '周二',
    value: '周二'
  },
  {
    label: '周三',
    value: '周三'
  },
  {
    label: '周四',
    value: '周四'
  },
  {
    label: '周五',
    value: '周五'
  },
  {
    label: '周六',
    value: '周六'
  },
  {
    label: '周日',
    value: '周日'
  }
]

const marks = [
  {
    label: 'BMI',
    value: 'BMI'
  },
  {
    label: '腰臀比',
    value: '腰臀比'
  },
  {
    label: '血压',
    value: '血压'
  },
  {
    label: '心率',
    value: '心率'
  },
  {
    label: '血糖',
    value: '血糖'
  },
  {
    label: '血氧',
    value: '血氧'
  }
]

let { creatorList, manageList, init } = useDict(templateType)

const formState_reset = (item) => {
  if (item) {
    Object.assign(formState, item)
  } else {
    Object.assign(formState, {
      id: '',
      templateName: '',
      templateType: templateType,
      content: {
        sings: undefined,
        // content: '',
        cronDate: [],
        cronTime: []
      },
      templateAffiliation: '公共模板',
      open: false
    })
  }
}

const formState = reactive({
  id: '',
  templateName: '',
  templateType: templateType,
  content: {
    sings: undefined,
    // content: '',
    cronDate: [],
    cronTime: []
  },
  templateAffiliation: '公共模板',
  open: false
})

const condition = ref([
  {
    title: '创建者',
    dataIndex: 'creator',
    type: 'select',
    value: '',
    data: creatorList
  },
  {
    title: '已配置管理路径',
    dataIndex: 'manageId',
    type: 'select',
    value: '',
    data: manageList
  },
  {
    title: '模板类型',
    dataIndex: 'templateAffiliation',
    type: 'select',
    value: '',
    data: [
      {
        value: '',
        label: '全部'
      },
      {
        value: '公共模板',
        label: '公共模板'
      },
      {
        value: '个人模板',
        label: '个人模板'
      }
    ]
  }
])

const conditionReset = () => {
  pagination.current = 1
  init()
  condition.value.map((v) => {
    v.value = ''
  })
  getList()
}

const pagination = reactive({
  current: 1,
  total: 0,
  pageSize: 10,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '50', '100']
})

const columns = ref([
  {
    title: '序号',
    dataIndex: 'no',
    key: 'no',
    align: 'left',
    width: '50px'
  },
  {
    title: '健康监测名称',
    dataIndex: 'templateName',
    key: 'templateName',
    align: 'left',
    minWidth: 100
  },
  {
    title: '模板类型',
    dataIndex: 'templateAffiliation',
    key: 'templateAffiliation',
    align: 'left',
    width: 100
  },
  {
    title: '已配置管理路径',
    dataIndex: 'managePath',
    key: 'managePath',
    align: 'left',
    minWidth: 200,
    ellipsis: true
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'left',
    width: '140px'
  },
  {
    title: '创建者',
    dataIndex: 'creator',
    key: 'creator',
    align: 'left',
    widht: '80px'
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    align: 'left',
    width: '200px'
  }
])

const loading = ref(false)
const List = ref([])

const getList = () => {
  loading.value = true
  const { current, pageSize } = pagination
  const obj = condition.value.reduce((c, v) => {
    if (v.value || v.value === 0) {
      return Object.assign(c, { [v.dataIndex]: v.value })
    } else {
      return c
    }
  }, {})
  const params = {
    page: current,
    limit: pageSize,
    templateName: templateName.value,
    templateType: templateType,
    ...obj
  }
  getTemplateList(params)
    .then((res) => {
      loading.value = false
      if (res.data.total > 0 && !res.data.list.length) {
        pagination.current = pagination.current - 1
        getList()
      } else {
        pagination.total = res.data.total
        List.value = res.data.list
      }
    })
    .catch((e) => {
      loading.value = false
    })
}

const paginationChange = (p) => {
  Object.assign(pagination, p)
  getList()
}

const onSearch = () => {
  pagination.current = 1
  getList()
}

onMounted(() => {
  getList()
})

const modal = reactive({
  open: false,
  type: 'save',
  loading: false,
  allowUpdate: true,
  title: '新建健康监测'
})

const modelForm = ref(null)

const modalShow = (item) => {
  modelForm.value?.clearValidate()
  if (item) {
    modal.title = '健康监测详情'
    modal.type = 'detail'
    const { id, templateName, content, managePath, templateAffiliation } = _.cloneDeep(item)
    const vo = JSON.parse(content)

    if (vo.cronDate) {
      vo.cronDate = vo.cronDate.split(',')
    } else {
      vo.cronDate = []
    }
    if (vo.cronTime) {
      vo.cronTime = vo.cronTime.split(',')
    } else {
      vo.cronTime = []
    }
    formState_reset({
      id,
      templateName,
      templateType,
      templateAffiliation,
      content: vo
    })
    modal.allowUpdate = managePath ? false : true
    modal.open = true
  } else {
    modal.title = '新建健康监测'
    modal.type = 'save'
    formState_reset()
    modal.allowUpdate = true
    modal.open = true
  }
}

const modalConfirm = () => {
  modelForm.value
    .validate()
    .then(() => {
      const { id, templateName, templateType, content, templateAffiliation } =
        _.cloneDeep(formState)
      content.cronDate = content.cronDate.join(',')
      content.cronTime = content.cronTime.join(',')
      const params = {
        id,
        templateName,
        templateType,
        templateAffiliation,
        content: JSON.stringify(content),
        platformId: store.userStore.platformId
      }

      modal.loading = true
      if (modal.type === 'save') {
        TemplateAdd(params)
          .then((res) => {
            modal.loading = false
            message.success('新建成功')
            conditionReset()
            modal.open = false
          })
          .catch((e) => {
            modal.loading = false
            console.log(e)
          })
      } else {
        TemplateUpdate(params)
          .then((res) => {
            modal.loading = false
            message.success('编辑成功')
            init()
            getList()
            modal.open = false
          })
          .catch((e) => {
            modal.loading = false
            console.log(e)
          })
      }
    })
    .catch((e) => {
      modal.loading = false
      // 表单校验失败
      console.log(e)
      modelForm.value.scrollToField(e.errorFields[0].name, {
        behavior: 'smooth',
        block: 'center'
      })
    })
}

const modalUpdate = () => {
  modal.type = 'update'
  modal.title = '编辑健康监测'
}

const delForm = (item) => {
  Modal.confirm({
    title: '删除',
    icon: createVNode(ExclamationCircleFilled, {
      style: {
        color: 'var(--color--danger)'
      }
    }),
    content: '确定删除该监测么',
    okText: '确定',
    okButtonProps: {
      danger: true,
      type: 'primary'
    },
    cancelText: '取消',
    onOk() {
      console.log('OK')
      TemplateDel(item.id).then(() => {
        message.success('删除成功')
        init()
        getList()
      })
    },
    onCancel() {
      console.log('Cancel')
    }
  })
}

const changeCronDate = (e) => {
  const value = e.target.value
  if (formState.content.cronDate.includes(value)) {
    const i = formState.content.cronDate.findIndex((v) => {
      return v === value
    })
    formState.content.cronDate.splice(i, 1)
  } else {
    formState.content.cronDate.push(value)
  }
}

const weekAll = () => {
  if (formState.content.cronDate.length !== weeks.length) {
    formState.content.cronDate = weeks.map((v) => {
      return v.value
    })
  } else {
    formState.content.cronDate = []
  }
}

const pickerFocus = () => {
  formState.open = true
}
const tagDel = (list, i) => {
  list.splice(i, 1)
  timePickerValue.value = null
}

const timePickerValue = ref()
const cronTimePush = (e) => {
  const set = new Set(formState.content.cronTime)
  set.add(e)
  formState.content.cronTime = Array.from(set)

  timePickerValue.value = null
}
</script>

<style lang="less" scoped>
@import './index.less';

.header {
  flex: 0 0 auto;
  display: flex;
  flex-direction: row;
  justify-content: space-between;

  .left {
    ::v-deep(.ant-space-item) {
      display: flex;
      flex-direction: row;
      align-items: center;
    }

    .title {
      font-size: 14px;
      font-family:
        PingFang SC,
        PingFang SC;
      font-weight: 400;
      color: #4e5969;
      line-height: 32px;
    }
  }

  .right {
    ::v-deep(.ant-space-item) {
      display: flex;
      flex-direction: row-reverse;
      align-items: center;
    }
  }
}

.main {
  flex: 1 1 auto;
  margin-top: 16px;
  overflow: hidden auto;

  :deep(.ant-table-wrapper) {
    .ant-table-cell {
      p {
        white-space: normal;
        margin-bottom: 0;

        .configuration {
          color: #3491fa;
          background: #e8f7ff;
          border-color: #3491fa;
          display: inline-block;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          max-width: 100%;
          margin-top: 10px;

          &:nth-child(1) {
            margin-top: 0;
          }
        }

        .success {
          color: #00b42a;
          background: #e8ffea;
          border-color: #00b42a;
          display: inline-block;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          max-width: 100%;
          margin-top: 10px;

          &:nth-child(1) {
            margin-top: 0;
          }
        }
        .groupTag {
          display: inline-block;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          max-width: 100%;
          margin-top: 10px;
          margin-right: 10px;
          &:nth-child(1) {
            margin-top: 0;
          }
        }
      }
    }
  }
}

.input {
  width: 210px !important;
}

.ant-form .ant-input {
  width: 100% !important;
}

.times {
  position: relative;
  .content {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    width: 100%;
    min-height: 32px;
    max-height: 84px;
    overflow: hidden auto;
    padding: 6px;
    line-height: 30px;
    border: 1px solid var(--color--primary);
    gap: 6px;
  }
  .pick {
    position: absolute;
    top: 0;
    left: 0;
    z-index: -1;
  }
}
</style>
